package com.leaf.lowcode.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.leaf.lowcode.API.PeronQueryApi;
import com.leaf.lowcode.API.VistorEventApi;
import com.leaf.lowcode.entity.ApptionmentBean;
import com.leaf.lowcode.entity.HkVistor;
import com.leaf.lowcode.entity.PersonInfoRequest;
import com.leaf.lowcode.entity.RecordsRequest;
import com.leaf.lowcode.mapper.ApptionmentMapper;
import com.leaf.lowcode.mapper.HkVisitorMapper;
import com.leaf.lowcode.utils.RegularInstance;
import com.leaf.lowcode.utils.jsontobean.JsonToBeanV;
import com.tencent.welink.iot.SubDeviceDTO;
import com.tencent.welink.iot.WelinkHttp;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;


/**
 * 访客预约统计
 * event.put("visitPurpose",apptionmentBean.getVisitPurpose());
 * event.put("orgName",orgName);
 * event.put("visitCount",1);
 */

@Component
public class VistorToal {
    @Autowired
    private HkVisitorMapper hkVisitorMapper;

    @Autowired
    private ApptionmentMapper apptionmentMapper;


  @Scheduled(initialDelay =  1000, fixedRate = 6*1000)
    void execute() {

       System.out.println("=======================================================");
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DAY_OF_MONTH, 0);
        //一天的开始时间 yyyy:MM:dd 00:00:00
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date dayStart = calendar.getTime();
        String pattern = "YYYY-MM-dd'T'HH:mm:ssZZ";
        String startStr = DateFormatUtils.format(dayStart, pattern);
        System.out.println("startStr" + startStr);
        //一天的结束时间 yyyy:MM:dd 00:00:00
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date dayEnd = calendar.getTime();
        String endStr = DateFormatUtils.format(dayEnd, pattern);
        System.out.println("startStr" + endStr);

        //   String  orgName;
        System.out.println("访客事件启动");
        VistorEventApi vistorEventApi = new VistorEventApi();
        RecordsRequest searchesRequest = new RecordsRequest();
        searchesRequest.setPageNo(1);
        searchesRequest.setPageSize(1000);
//        searchesRequest.setVisitEndTimeBegin(startStr);
//        searchesRequest.setVisitEndTimeEnd(endStr);
        /**
         *
         */
        String StringtoJson = vistorEventApi.eventSearch(searchesRequest);
        JSONObject vistorJson = JSON.parseObject(StringtoJson);
        System.out.println(vistorJson);
        JSONArray vistorList = (JSONArray) ((JSONObject) vistorJson.get("data")).get("list");
        //今日来访客预约数量


        String appointment = vistorEventApi.appointmentSearch(searchesRequest);
        JSONObject appointmentJson = JSON.parseObject(appointment);
        System.out.println(appointmentJson);
        JSONArray appointmentList = (JSONArray) ((JSONObject) appointmentJson.get("data")).get("list");
        //访客预约人数


        /**
         * 被访记录
         */
        ApptionmentBean apptionmentBean=new ApptionmentBean();

        ApptionmentBean flag1;

        /**
         * 今日预约记录
         */
        String json=vistorEventApi.appointmentSearch(searchesRequest);

        JSONObject apptionmentjson=JSON.parseObject(json);

        JSONArray apption = (JSONArray) ((JSONObject) apptionmentjson.get("data")).get("list");

        JsonToBeanV<ApptionmentBean>  jsonToBeanV=new JsonToBeanV<ApptionmentBean>();

        for(int i=0;i<apption.size();i++) {
            JSONObject jsonbean = (JSONObject) apption.get(i);
            apptionmentBean.setVisitorStatus((Integer) jsonbean.get("visitorStatus"));
            apptionmentBean.setReceptionistCode((String) jsonbean.get("receptionistCode"));
            apptionmentBean = jsonToBeanV.tansfrom(apptionmentBean, jsonbean);
            System.out.println("apptionMentBeanID"+apptionmentBean.getOrderId());
            flag1 = apptionmentMapper.selectId(apptionmentBean.getOrderId());
            if (flag1 == null) {
                System.out.println("访客预约不存在");
                if(apptionmentBean.getVisitPurpose().equals("测试"))
                {
                    apptionmentBean.setVisitPurpose("参加会议");
                }else if(apptionmentBean.getVisitPurpose().equals("0"))
                {
                    apptionmentBean.setVisitPurpose("客户拜访");
                }
                else if(apptionmentBean.getVisitPurpose().equals("0"))
                {
                    apptionmentBean.setVisitPurpose("交流学习");
                } else if(apptionmentBean.getVisitPurpose().equals(""))
                {
                    apptionmentBean.setVisitPurpose("其他");
                }else {
                    apptionmentBean.setVisitPurpose("受邀拜访");
                }

                int i1 = apptionmentMapper.insert(apptionmentBean);
                PeronQueryApi peronQueryApi= new PeronQueryApi();
                ArrayList<String> list =new ArrayList();
                PersonInfoRequest personInfoRequest=new PersonInfoRequest();
                personInfoRequest.setParamName("personId");
                list.add(apptionmentBean.getReceptionistId());
                personInfoRequest.setParamValue(list);
                String personinfo=peronQueryApi.personInfoSearch(personInfoRequest);
                JSONObject personJson= (JSONObject) JSON.parse(personinfo);
                JSONArray json1 = (JSONArray) ((JSONObject)personJson.get("data")).get("list");
                String  orgName = null;
                for(int j=0;j<json1.size();j++)
                {
                    orgName  = (String) ((JSONObject) json1.get(j)).get("orgName");
                }
                if (i1 == 1) {
                    System.out.println("插入成功");
                }

                List<SubDeviceDTO> subDeviceDTOList = RegularInstance.subDeviceDTOList;
                System.out.println("======================进入道一云=================");
                JSONObject events = new JSONObject();
                JSONObject event = new JSONObject();
                JSONObject propertie = new JSONObject();
                JSONObject standardData = new JSONObject();
                JSONObject properties =new JSONObject();
                standardData.put("reportTs", System.currentTimeMillis());
                JSONObject profile = new JSONObject();
                profile.put("modelId", 200731);
                profile.put("poiCode", "w0717006");
                profile.put("appType","visitor");
                standardData.put("profile", profile);
                WelinkHttp wh = new WelinkHttp(RegularInstance.registerData1, RegularInstance.loginData);


                event.put("visitPurpose",apptionmentBean.getVisitPurpose());

                event.put("orgName",orgName);
                System.out.println("预约目的"+apptionmentBean.getVisitPurpose());
                System.out.println("预约来访部门"+orgName);
                event.put("visitCount",1);
                event.put("eventType", 1);
                event.put("eventTs", System.currentTimeMillis());
                event.put("describe", "");
                events.put("door_count",event);
                standardData.put("events", events);
                standardData.put("properties", properties);
                //standardData.put("properties", "{}");
                try {
                    System.out.println("上传数据");
                    String devRunEvent = JSONObject.toJSONString(standardData, SerializerFeature.WriteMapNullValue);
                    System.out.println("发送设备运行时事件数据==" + devRunEvent);
                    System.out.println("--------------------------------开始传输设备运行时事件数据");
                    wh.sendMessage(RegularInstance.loginData.load(), 80000, Long.parseLong("300000000000209094"), devRunEvent, true);
                } catch (Exception e) {
                    System.out.println("设备运行时事件数据传输出现异常");
                }

            }else {
                System.out.println("访客存在");
            }
        }
    }
}
